package com.xcalendar.servlets;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.xcalendar.constant.XConstants;
import com.xcalendar.database.dao.EventDAO;
import com.xcalendar.database.dao.LocationDAO;
import com.xcalendar.database.table.Event;
import com.xcalendar.database.table.Location;
import com.xcalendar.database.table.User;
import com.xcalendar.exception.IncorrectNameOrPasswordException;
import com.xcalendar.management.UserManager;
import com.xcalendar.managementImpl.UserManagerImpl;

@SuppressWarnings("serial")
public class LoginController extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		StringBuilder error = new StringBuilder();
		UserManager um = new UserManagerImpl();
		HttpSession session = request.getSession(true);
		EventDAO eventDao = new EventDAO();
		LocationDAO locationDAO = new LocationDAO();
	    
		User user = null;
		try {
			user = um.login(userName, password);
		} catch (IncorrectNameOrPasswordException e) {
			error.append("Incorrect username Or wrong password !");
		    request.setAttribute(XConstants.WRONY_MESSAGE, error.toString());
		    RequestDispatcher view = request.getRequestDispatcher("welcome.jsp");
		    view.forward(request, response);
		}
		
		//////////////////////////////////////////////////////////////*
		
		/*Location newLocation = new Location();
		newLocation.setLocationName("School");
		newLocation.setLatitude(48.78962);
		newLocation.setLongitude(2.3637);
		newLocation.setUserKey(user.getKey());
		locationDAO.addLocation(newLocation);
		try {
			user = um.login(userName, password);
		} catch (IncorrectNameOrPasswordException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}*/
		////////////////////////////////////////////////////////////////
		
		JSONArray jArray = new JSONArray();
		List<Event> events = user.getEvents();
		for (Event event : events) {
			Key k = event.getKey();
			event = eventDao.readEvent(k);
			JSONObject obj = new JSONObject();
			
			try {
				SimpleDateFormat time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				obj.put("id", KeyFactory.keyToString(event.getKey()));
				obj.put("title", event.getTitle());
				if (event.getLocationKey()!=null) {
					obj.put("locationKey", KeyFactory.keyToString(event.getLocationKey()));
					LocationDAO l = new LocationDAO();					
					obj.put("locationName", l.readLocation(event.getLocationKey()).getLocationName());
					//System.out.println(l.readLocation(event.getLocationKey()).getLocationName());
				}
				obj.put("description", event.getDescription());
				obj.put("start", time.format(event.getStartTime()));
				obj.put("end", time.format(event.getEndTime()));
				obj.put("allDay", false);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			jArray.put(obj);	
		}
		jArray.put(events.size());

		JSONArray jArrayLocation = new JSONArray();
		List<Location> locations = user.getLocations();
		for (Location location : locations) {
			Key k = location.getKey();
			location = locationDAO.readLocation(k);
			JSONObject obj = new JSONObject();
			
			try {
				obj.put("key", KeyFactory.keyToString(location.getKey()));
				obj.put("locationName", location.getLocationName());
				obj.put("latitude", location.getLatitude());
				obj.put("longitude", location.getLongitude());
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			jArrayLocation.put(obj);	
		}
		//jArrayLocation.put(locations.size());
		//System.out.println(user.getUserName()+jArrayLocation.toString());
		if (user != null) {
			session.setAttribute(XConstants.SESSION_USER, user);
			session.setAttribute(XConstants.ISLOGGED, "true");
			session.setAttribute(XConstants.JSONEVENTS, jArray.toString());
			session.setAttribute(XConstants.JSONLOCATIONS, jArrayLocation.toString());
			//System.out.println(jArray.toString());
			//System.out.println(jArrayLocation.toString());
			RequestDispatcher view = request.getRequestDispatcher("homepage_calendar.jsp");
		    view.forward(request, response);
		}
		
	}
}
